﻿using System;
using System.Threading;
//using System.Runtime.Remoting.Messaging;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace Spacer {
	public delegate object Worker();
	public delegate object HandleResult( IAsyncResult result );
	public delegate void   Callback( object result );

	// ----------

    public class PleaseWait : Activity {
		public PleaseWait( IAsyncResult handle, HandleResult async_done, Callback finished ) {
			Handle = handle;
			HandleResult = async_done;
			Callback = finished;
		}

		public PleaseWait( Worker worker, Callback finished ) {
			/*Handle = worker.BeginInvoke(
				data,
				handle => {
					Worker w = (Worker)((AsyncResult)handle).AsyncDelegate;
					((PleaseWait)handle.AsyncState).Value = w.EndInvoke( handle );
				},
				this
			);*/

			Worker = worker;
			Thread = new Thread( new ParameterizedThreadStart(DoWork) );
			Thread.Start( this );

			Callback = finished;
		}

		public void DoWork( object self ) {
			((PleaseWait)self).Value = ((PleaseWait)self).Worker();
		}

		// ----------

        public void Initialize() {
        }

        public void Paused() {

        }

        public void Resumed() {

        }

        public void Shutdown() {
        }

        public void Update() {
        }

        public void DrawWorld() {
        }

        public void DrawOverlay() {
            //Draw Black Background, or BLACKGROUND!
            Surface.DrawColor = Color.Black;
            Surface.DrawRect(Vector2.Zero, new Vector2(Surface.Width, Surface.Height), Vector2.Zero, 0f, Layer.LAYER_20);

            //Draw the game's logo
            Surface.DrawColor = Color.Yellow;
            Surface.DrawString(
				"Orbitronio",
				"Please wait",
				new Vector2( 10f, Surface.Height - 10f ),
				new Vector2( 0f, 1f ),
				0f
			);
        }

        public bool IsModal() {
            return false;
        }

        public bool IsTransparent() {
            return true;
        }

        public bool IsFinished() {
			if( !Finished ) {
				if( Handle != null && Handle.IsCompleted ) {
					if( HandleResult != null )
						Value = HandleResult( Handle );

					if( Callback != null )
						Callback( Value );
				
					Finished = true;
				} else if( Thread != null && Thread.ThreadState == ThreadState.Stopped ) {
					if( Callback != null )
						Callback( Value );

					Finished = true;
				}
			}

			return Finished;
        }

        // ----------

		private bool Finished { get; set; }
        private IAsyncResult Handle { get; set; }

		private Thread Thread { get; set; }
		private Worker Worker { get; set; }

		private HandleResult HandleResult { get; set; }
		private Callback Callback { get; set; }

		public object Value { get; set; }
    }
}
